package com.dnjn.happiness.emo.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.emo.domain.EmoUserRecordPos;
import com.dnjn.happiness.emo.mapper.EmoUserRecordPosMapper;
import com.dnjn.happiness.emo.service.IEmoUserRecordPosService;
import com.dnjn.happiness.emo.webapi.c3v8.in.PosRecordIn;
import com.dnjn.happiness.emo.webapi.c3v8.out.C3v8Out;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 消费记录Service业务层处理
 * 
 * @author happiness
 * @date 2024-03-13
 */
@Service
public class EmoUserRecordPosServiceImpl extends ServiceImpl<EmoUserRecordPosMapper, EmoUserRecordPos>  implements IEmoUserRecordPosService
{

    @Autowired
    private RemoteUserService userService;

    @Override
    public void insert(EmoUserRecordPos pos) {
        baseMapper.insert(pos);
    }

    @Override
    public AjaxResult queryPosRecordByTime(String startTime, String endTime) {
        if (!isLegalDate(startTime.length(),startTime,"yyyy-MM-dd HH:mm:ss") || !isLegalDate(endTime.length(),endTime,"yyyy-MM-dd HH:mm:ss")){
            return AjaxResult.error("时间格式不正确！");
        }
        List<SysUser> userListAll = new ArrayList<>();
        R<List<SysUser>> result = userService.getUserListAll(SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
            userListAll = result.getData();
        }
        //根据工号去查询
        String yesterday = LocalDate.now().minusDays(1).toString();
        PosRecordIn posRecordIn = new PosRecordIn()
                .setStartTime(startTime)
                .setEndTime(endTime)
                .setSecId(0);
        posRecordIn.setPageSize(1000);
        for (SysUser user : userListAll) {
            String empno = user.getEmpno();
            if (StringUtils.isNotEmpty(empno)){
                posRecordIn.setPageIndex(1);
                posRecordIn.setEmpNo(empno);
                C3v8Out<Object> posRes =  posRecordIn.send();
                if (Objects.isNull(posRes)){
                    return AjaxResult.error("接口调用失败!");
                }
                if ( !posRes.getCode().equals(0) || Objects.isNull(posRes.getData()) ||
                        CollectionUtils.isEmpty(posRes.getData().getDatalist()) || posRes.getData().getTotalCount().equals(0)){
                    continue;
                }else {
                    for (Object obj : posRes.getData().getDatalist()) {
                        //落库
//                        EmoUserRecordPos pos = new ObjectMapper().convertValue(obj, EmoUserRecordPos.class);
                        EmoUserRecordPos pos = JSON.parseObject(JSON.toJSONString(obj), EmoUserRecordPos.class);
                        pos.setUserId(user.getUserId());
                        pos.setEmpno(user.getEmpno());
                        baseMapper.insert(pos);
                    }
                    Integer pageCount = posRes.getData().getPageCount();
                    if (pageCount > 1){
                        int INDEX = 2;
                        for (Integer i = 0; i < pageCount; i++) {
                            posRecordIn.setPageIndex(INDEX);
                            C3v8Out<Object> res = posRecordIn.send();
                            if (Objects.isNull(posRes)){
                                return AjaxResult.error("接口调用失败");
                            }
                            List<Object> dataList = res.getData().getDatalist();
                            for (Object obj : dataList) {
                                //落库
                                EmoUserRecordPos pos = (EmoUserRecordPos) obj;
                                pos.setUserId(user.getUserId());
                                baseMapper.insert(pos);
                            }
                            INDEX++;
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult insertYesterdayPosRecord() {
        //根据工号去查询
        String startTime = LocalDate.now().minusDays(1) + " 00:00:00";
        String endTime = LocalDate.now().minusDays(1) + " 23:59:59";
        return queryPosRecordByTime(startTime,endTime);
    }

    /**
     * 根据时间 和时间格式 校验是否正确
     * @param length 校验的长度
     * @param sDate 校验的日期
     * @param format 校验的格式
     * @return
     */
    public static boolean isLegalDate(int length, String sDate,String format) {
        int legalLen = length;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return false;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }
}
